package com.nonintrusive.client.service;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.nonintrusive.client.GlobalNonIntrusive;
import com.nonintrusive.client.database.ClientDB;
import com.nonintrusive.client.send.R;
import com.nonintrusive.client.tabs.MainActivity;
import com.nonintrusive.message.MessageNonIntrusive;

public class ClientService extends Service {
	private static final String TAG = "ClientService";
	private static final long INTERVAL = 1000 * 5; // milliseconds
	private Timer mTimer = new Timer();
	private NotificationManager mNotificationManager;

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "service started");
		startservice();

	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	private void startservice() {
		mTimer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				updateAnswers();
				updateNewQuestions();
			}
		}, 0, INTERVAL);
	}

	private void updateAnswers() {

		ContentResolver cr = getContentResolver();
		ContentValues values = new ContentValues();
		try {
			Socket socket = new Socket(GlobalNonIntrusive.SERVER_IP,
					GlobalNonIntrusive.PORT);
			ObjectOutputStream oos = new ObjectOutputStream(socket
					.getOutputStream());

			ObjectInputStream ois = new ObjectInputStream(socket
					.getInputStream());

			Log.d(TAG, "send ANY_ANSWERS");
			// send qType = ANY_ANSWERS
			MessageNonIntrusive sendMessage = new MessageNonIntrusive();
			sendMessage.type = MessageNonIntrusive.ANY_ANSWERS;
			synchronized (GlobalNonIntrusive.clientID) {
				sendMessage.senderId = GlobalNonIntrusive.clientID;
			}

			oos.writeObject(sendMessage);

			// read answer
			MessageNonIntrusive recvMessage = (MessageNonIntrusive) ois
					.readObject();
			int newAnswersQ = Integer.parseInt(recvMessage.content);
			Log.d(TAG, "how many answ? " + newAnswersQ);

			for (int i = 0; i < newAnswersQ; i++) {
				// receive answers
				recvMessage = (MessageNonIntrusive) ois.readObject();
				Log.d(TAG, "received: " + recvMessage);

				// add answer to DB
				values.put(ClientDB.NR_ANSWERS,
						recvMessage.nrAnswersToString());
				values.put(ClientDB.TIMESTAMP,
						System.currentTimeMillis());
				cr.update(ClientDB.CONTENT_URI, values,
						ClientDB.QUESTION_ID + " = "
								+ recvMessage.questionId, null);
				values.clear();
			}
			ois.close();
			oos.close();
			socket.close();

			// notification
			if (newAnswersQ > 0) {
				mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

				int icon = R.drawable.icon;
				CharSequence text = "Notification Text: you've received new answers!";
				CharSequence contentTitle = "Notification Title";
				CharSequence contentText = "At click.";
				long when = System.currentTimeMillis();

				Intent intent = new Intent(ClientService.this,
						MainActivity.class);
				PendingIntent contentIntent = PendingIntent
						.getActivity(ClientService.this, 0, intent, 0);
				Notification notification = new Notification(icon,
						text, when);
				notification.flags = Notification.FLAG_AUTO_CANCEL;
				notification.setLatestEventInfo(ClientService.this,
						contentTitle, contentText, contentIntent);
				mNotificationManager.notify(
						GlobalNonIntrusive.SIMPLE_NOTFICATION_ID,
						notification);
				Log.d(TAG, "notification launched");
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	
	private void updateNewQuestions() {
		ContentResolver cr = getContentResolver();
		ContentValues values = new ContentValues();
		try {
			Socket socket = new Socket(GlobalNonIntrusive.SERVER_IP,
					GlobalNonIntrusive.PORT);
			ObjectOutputStream oos = new ObjectOutputStream(
					socket.getOutputStream());

			ObjectInputStream ois = new ObjectInputStream(
					socket.getInputStream());

			// send qType = ANY_QUESTIONS
			Log.d(TAG, "send ANY_QUESTIONS");
			MessageNonIntrusive sendMessage = new MessageNonIntrusive();
			sendMessage.type = MessageNonIntrusive.ANY_QUESTIONS;
			synchronized (GlobalNonIntrusive.clientID) {
				sendMessage.senderId = GlobalNonIntrusive.clientID;
			}
			oos.writeObject(sendMessage);

			// read new questions
			MessageNonIntrusive recvMessage = (MessageNonIntrusive) ois
					.readObject();
			int newQuestions = Integer.parseInt(recvMessage.content);
			Log.d(TAG, "how many new q? " + newQuestions);
			for (int i = 0; i < newQuestions; i++) {
				recvMessage = (MessageNonIntrusive) ois.readObject();
				Log.d(TAG, "received: " + recvMessage);
				values.put(ClientDB.QUESTION_ID, recvMessage.questionId);
				values.put(ClientDB.MESSAGE, recvMessage.content);
				values.put(ClientDB.ANSWER1, recvMessage.answers.get(0));
				values.put(ClientDB.ANSWER2, recvMessage.answers.get(1));
				values.put(ClientDB.TAGS, recvMessage.tags);
				values.put(ClientDB.IS_MY_QUESTION, false);
				values.put(ClientDB.IS_ANSWERED, false);
				values.put(ClientDB.TIMESTAMP, System.currentTimeMillis());
				cr.insert(ClientDB.CONTENT_URI, values);
				values.clear();
			}
			ois.close();
			oos.close();
			socket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onDestroy() {
		stopservice();
	}

	private void stopservice() {
		if (mTimer != null) {
			mTimer.cancel();
		}
	}
}
